package com.kaia.shoebox.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.kaia.shoebox.db.dao.TodoItem;

public class DbHelper extends OrmLiteSqliteOpenHelper {

	// ------------------------------------------------------------------
	// Constants
	// ------------------------------------------------------------------

	private static final String DATABASE_NAME = "shoebox.db";
	private static final int DATABASE_VERSION = 1;

	private static final String TAG = DbHelper.class.getSimpleName();

	// ------------------------------------------------------------------
	// Attributes
	// ------------------------------------------------------------------

	private Dao<TodoItem, Integer> dao;
	private RuntimeExceptionDao<TodoItem, Integer> runtimeDao;

	public DbHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	// ------------------------------------------------------------------
	// System Methods
	// ------------------------------------------------------------------

	@Override
	public void onCreate(SQLiteDatabase db, ConnectionSource source) {
		try {
			Log.i(TAG, "onCreate");
			TableUtils.createTable(source, TodoItem.class);
		} catch (SQLException e) {
			Log.e(TAG, "couldn't create database", e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, ConnectionSource source,
			int oldVer, int newVer) {
		// TODO See how to do it without deleting tables

	}

	@Override
	public void close() {
		super.close();
		runtimeDao = null;
	}

	// ------------------------------------------------------------------
	// Methods
	// ------------------------------------------------------------------

	public RuntimeExceptionDao<TodoItem, Integer> getRuntimeDao() {
		if (runtimeDao == null) {
			runtimeDao = getRuntimeExceptionDao(TodoItem.class);
		}
		return runtimeDao;
	}

	public Dao<TodoItem, Integer> getTodoDao() throws SQLException {
		if (dao == null) {
			dao = getDao(TodoItem.class);
		}
		return dao;
	}
}